/**
 * Created by chenyong on 2015/7/16.
 */

var request = require('request');
var _apiToken = null;

var _getApiToken = function(){
    var oauth = {
        grant_type:'client_credentials',
        client_id:'7d21c0f1-78b8-4078-a8cc-89726b228e4d',
        client_secret:'fGus4O82u8fBsVinWXPQBFR/XHEX8cco/HCf/khR8w0=',
        resource:'http://srv.bigpixel.cn'
    };
    var token_endpoint = 'https://login.chinacloudapi.cn/a76b6aab-8a67-41fd-87f2-23c2a087d961/oauth2/token?api-version=1.0';
    request.post({url:token_endpoint, form: oauth}, function(err,httpResponse,body){
        if(!err)
        {
            _apiToken = JSON.parse(body);;
            console.log(_apiToken);
            var delayTime = (parseInt(_apiToken.expires_in) - 100)*1000;
            setTimeout(_getApiToken,delayTime);
        }
    })
};

_getApiToken();

var _getcachedToken = function(){
    return _apiToken.access_token;
};

exports.getcachedToken = _getcachedToken;